package com.itcodai.course16.session;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.UUID;

/**
 * 自定义的sessionManager  DefaultWebSessionManager
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    /**
     *
     *
     * 指定sessionId获取方式
     *
     *      头信息中具有sessionId
     *          请求头：Authorization : session
     *           String id = WebUtils.toHttp(request).getHeader("Authorization");
     * @param request
     * @param response
     * @return
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //获取请求头Authorization中的数据
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        if (StringUtils.isEmpty(id)){
            //如果没有携带，可以生成新的sessionId
//            String id1 = UUID.randomUUID().toString().replace("-", "");
            return super.getSessionId(request,response);
        }else {
            //返回sessionId
            //来源 请求头
            //sessionId是什么
            //sessionId要不还要验证
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        }
    }
}
